import { Table } from 'antd';
import { v4 as uuidv4 } from 'uuid';

interface DataPreviewProps {
    dataSource: any;
    columns: any;
}

export const DataPreview = memo<DataPreviewProps>((props) => {

    const [dataSource, setDataSource] = useState<any>([]);
    const [expandedColumns, setExpandedColumns] = useState<any>([]);
    const [expandedDataSource, setExpandedDataSource] = useState<any>([]);

    // 构造数组
    const buildExpandList = (expandList: any) => {
        if (!expandList || !Array.isArray(expandList)) {
            return null;
        }

        const newData = expandList.map((item: any) => {
            return {
                id: uuidv4(),
                ...item
            };
        });

        // 提取嵌套数组中的键作为 columns
        const columns = Object.keys(expandList[0]).map(key => {
            return {
                title: key.charAt(0).toUpperCase() + key.slice(1),
                dataIndex: key,
                key,
            };
        });
        setExpandedColumns(columns);
        setExpandedDataSource(newData);
    };

    const expandedRowRender = () => {
        return (
            <Table
                rowKey="id"
                columns={expandedColumns}
                dataSource={expandedDataSource}
                pagination={false}
            />
        );
    };

    useEffect(() => {
        const newDataSource = props.dataSource ? props.dataSource.map((item: any) => {
            const newItem = {
                ...item, // 拷贝原有属性
              };
            
              // 遍历对象的每个属性
              for (const key in newItem) {
                if (newItem.hasOwnProperty(key) && Array.isArray(newItem[key])) {
                  buildExpandList(newItem[key]);
                  // 如果属性值是数组，替换为 "见子表"
                  newItem[key] = '见子表';
                }
              }
            
              return newItem;
        }) : [];
        setDataSource(newDataSource);
    }, [props.dataSource]);

    return (
        <>
            <p>数据预览</p>
            <div className="max-h-500 mt-8" style={{ width: '100%', overflow: 'auto' }}>
                {
                    expandedColumns.length === 0 ? (
                        <Table
                            rowKey="id"
                            dataSource={dataSource}
                            columns={props.columns}
                            pagination={false}
                        />
                    ) : (
                        <Table
                            rowKey="id"
                            dataSource={dataSource}
                            columns={props.columns}
                            pagination={false}
                            expandable={{ expandedRowRender, defaultExpandedRowKeys: ['0'] }}
                        />
                    )
                }
            </div>
        </>
    );
});
